<template>
  <div class="container">
    <!-- 左侧：学习路径 -->
    <div class="left-panel">
      <div class="exam-container">
        <div ref="chart" style="width: 100%; height: 600px;"></div>
      </div>
    </div>

    <!-- 右侧：知识图谱 -->
    <div class="right-panel">
      <div id="knowledge-graph" style="width: 100%; height: 600px;"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getpath } from "@/api/class/class_choose";
import { getnodeData } from "@/api/pics/pic";

export default {
  name: "CombinedView",
  data() {
    return {
      pathList: [], // 存储路径信息（原始字符串数组）
      treeData: {}, // 解析后的树状数据
      graphData: {
        nodes: [],
        links: []
      }
    };
  },
  created() {
    const classId = this.$route.query.classId;
    getpath(classId)
      .then((response) => {
        this.pathList = response; // 直接赋值字符串数组
        this.parsePathData(this.pathList); // 解析路径数据
        this.initChart(); // 初始化图表
      })
      .catch((error) => {
        console.error("获取路径失败:", error);
      });

    this.fetchGraphData();
  },
  methods: {
    handleClose() {
      const obj = { path: "/myClass/class_choose" };
      this.$tab.closeOpenPage(obj);
    },
    parsePathData(pathList) {
      if (!pathList || pathList.length === 0) return;

      // 构建树状数据结构
      const treeData = {
        children: [] // 直接使用 children 作为根节点
      };

      pathList.forEach(path => {
        const nodes = path.split("&");
        const mainNodeName = nodes[0]; // 第一个为一级节点

        // 查找或创建一级节点
        let mainNode = treeData.children.find(child => child.name === mainNodeName);
        if (!mainNode) {
          mainNode = {
            name: mainNodeName,
            children: []
          };
          treeData.children.push(mainNode);
        }

        // 添加二级节点（从第二个开始）
        for (let i = 1; i < nodes.length; i++) {
          const node = nodes[i].trim();
          if (node) {
            const [nodeName, url] = node.split(" "); // 分割节点名称和 URL
            const newNode = {
              name: nodeName,
              url: url || '' // 提取 URL
            };
            mainNode.children.push(newNode);
          }
        }
      });

      // 如果 treeData.children 只有一个子节点，则直接使用该子节点作为根节点
      if (treeData.children.length === 1) {
        this.treeData = treeData.children[0];
      } else {
        this.treeData = treeData;
      }
    },
    initChart() {
      const chartDom = this.$refs.chart;
      const myChart = echarts.init(chartDom);

      const option = {
        title: {
          text: '学习路径',
          top: 'top',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          triggerOn: 'mousemove',
          formatter: function (params) {
            if (params.data.url) {
              return `${params.name}<br/><a href="/class/class_choose/study?classId=${this.$route.query.classId}" target="_blank">
    点击查看详情
  </a>`;
            }
            return params.name;
          }
        },
        series: [
          {
            type: 'tree',
            data: [this.treeData], // 使用解析后的树状数据
            top: '8%',
            left: '10%', // 页面靠左一点
            bottom: '14%',
            right: '20%',
            symbolSize: 6,
            edgeShape: 'polyline',
            edgeForkPosition: '30%',
            initialTreeDepth: 10,
            lineStyle: {
              width: 1
            },
            // 设置 orient 为 'LR' 实现左右布局
            orient: 'LR',

            label: {
              backgroundColor: 'transparent',
              position: 'left', // 标签在右侧
              verticalAlign: 'middle',
              align: 'right',
              fontSize: 12,
              color: '#333'
            },

            leaves: {
              label: {
                position: 'left', // 叶子节点标签在右侧
                verticalAlign: 'middle',
                align: 'right',
                fontSize: 12
              }
            },
            expandAndCollapse: false,
            nodeAlign: 'left',
            animationDuration: 550,
            animationDurationUpdate: 750
          }
        ]
      };

      myChart.setOption(option);

      // 添加节点点击事件
      myChart.on('click', (params) => {
        const classId = this.$route.query.classId;
        this.$router.push({
          path: '/class/class_choose/study',
          query: { classId }
        });
      });

      window.addEventListener('resize', () => {
        myChart.resize();
      });
    },
    fetchGraphData() {
      const classId = this.$route.query.classId;
      getnodeData(classId)
        .then((response) => {
          console.log("response=", response);
          this.processGraphData(response);
          this.initKnowledgeGraph();
        })
        .catch(error => {
          console.error("Error fetching graph data:", error);
        });
    },
    processGraphData(data) {
      if (!data || !data.length) return;

      // 清空现有数据
      this.graphData.nodes = [];
      this.graphData.links = [];

      // 处理根节点
      const rootNode = data[0];
      this.addNode(rootNode.name, 0);

      // 递归处理子节点
      this.processChildren(rootNode.children, rootNode.name, 1);
    },
    processChildren(children, parentName, level) {
      if (!children || !children.length) return;

      children.forEach(child => {
        // 添加当前节点
        this.addNode(child.name, level);

        // 添加与父节点的连线
        this.addLink(parentName, child.name);

        // 递归处理子节点
        if (child.children && child.children.length) {
          this.processChildren(child.children, child.name, level + 1);
        }
      });
    },
    addNode(name, level) {
      // 避免重复添加节点
      if (this.graphData.nodes.some(node => node.name === name)) return;

      // 根据层级设置不同的大小和颜色
      const node = {
        name: name,
        category: level,
        symbolSize: 30 - level * 5,
        itemStyle: {
          color: this.getColorByLevel(level)
        }
      };
      this.graphData.nodes.push(node);
    },
    addLink(source, target) {
      this.graphData.links.push({
        source: source,
        target: target
      });
    },
    getColorByLevel(level) {
      const colors = [
        '#c23531',  // 红色 - 根节点
        '#2f4554',  // 深蓝 - 第一级
        '#61a0a8',  // 浅蓝 - 第二级
        '#d48265',  // 橙色 - 第三级
        '#91c7ae'   // 绿色 - 第四级
      ];
      return colors[Math.min(level, colors.length - 1)];
    },
    initKnowledgeGraph() {
      const myChart = echarts.init(document.getElementById('knowledge-graph'));

      const option = {
        title: {
          text: '知识图谱',
          top: 'top',
          left: 'center'
        },
        tooltip: {},
        legend: {
          data: ['根节点', '一级节点', '二级节点', '三级节点'],
          orient: 'vertical',
          right: 10,
          top: 'center'
        },
        series: [{
          type: 'graph',
          layout: 'force',
          force: {
            repulsion: 200,
            edgeLength: 100,
            gravity: 0.1
          },
          roam: true,
          draggable: true,
          focusNodeAdjacency: true,
          data: this.graphData.nodes,
          links: this.graphData.links,
          categories: [
            {name: '根节点'},
            {name: '一级节点'},
            {name: '二级节点'},
            {name: '三级节点'}
          ],
          label: {
            show: true,
            position: 'right',
            formatter: '{b}'
          },
          lineStyle: {
            color: 'source',
            curveness: 0.2
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: {
              width: 3
            }
          }
        }]
      };

      myChart.setOption(option);

      window.addEventListener('resize', () => {
        myChart.resize();
      });
    }
  }
};
</script>
<style scoped>
.container {
  display: flex;
  width: 100%;
  height: 100%;
}

.left-panel, .right-panel {
  flex: 1;
  padding: 20px;
}

.exam-container {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
}

#knowledge-graph {
  width: 100%;
  height: 100%;
  border: 1px solid #eee;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
